package cls.elmp.atf.servlet;

import com.service.atf.base.core.ITFDBService;
import com.service.atf.base.model.TFInfo;
import com.service.atf.base.utils.ATFConstants;

import java.io.File;
import java.util.*;

/**
 * Created by IntelliJ IDEA.
 * User: luotao
 * Date: 12-3-17
 * Time: PM9:06
 * To change this template use File | Settings | File Templates.
 */
public class MockTFDBService implements ITFDBService {
    private int tfCode = 0;

    boolean firstTF = false;

    public MockTFDBService(boolean firstTF) {
        this.firstTF = firstTF;
    }

    public String fillString(int id) {
        String s = String.valueOf(id);
        int len = s.length();
        StringBuffer str = new StringBuffer(s);
        int j = 4 - len;
        for (int i = 0; i < j; i++) {
            str.insert(0, "0");
        }
        return str.toString();
    }

    @Override
    public TFInfo findById(int id) {
        String s_date = "";
        String fileName = s_date.substring(2) + fillString(id) + ".tf";
        File f = new File(ATFConstants.TF_PATH_PRIFIX + fileName);
        if (!f.exists()) {
            return null;
        }
        TFInfo tfInfo = new TFInfo();
        tfInfo.setAtfCode(id);
        tfInfo.setAtfCreateDate(new Date());
        tfInfo.setAtfFilePath(f.getAbsolutePath());
        tfInfo.setAtfNextCode(id + 1);
        tfInfo.setAtfPrevCode(id - 1);
        tfInfo.setAtfStatus("0");
        return tfInfo;
    }

    @Override
    public TFInfo getLastATF() {
        File f = new File(ATFConstants.TF_PATH_PRIFIX);
        if (!f.isDirectory()) return null;
        List<File> list = new ArrayList<File>();
        File[] files = f.listFiles();
        if (files == null || files.length == 0) return null;
        for (File file : files) {
            if (!file.getName().endsWith(".tf")) continue;
            list.add(file);
        }
        if (list.size() == 0) {
            return null;
        }
        Collections.sort(list, new Comparator<File>() {
            @Override
            public int compare(File s, File s1) {
                return s1.getName().compareTo(s.getName());
            }
        });
        File file = list.get(0);
        TFInfo tfInfo = new TFInfo();
        String newID = file.getName().substring(9, 10);
        int i_id = Integer.valueOf(newID);
        tfCode = i_id;
        tfInfo.setAtfCode(Integer.valueOf(newID));
        tfInfo.setAtfCreateDate(new Date());
        tfInfo.setAtfFilePath(file.getAbsolutePath());
        tfInfo.setAtfNextCode(i_id + 1);
        tfInfo.setAtfPrevCode(i_id - 1);
        tfInfo.setAtfStatus("0");
        return tfInfo;

    }


    @Override
    public int getTFCode() {
        tfCode += 1;
        return tfCode;
    }

    @Override
    public void insertTF(TFInfo nextTF) {

    }

    @Override
    public void tfComplate(int atfCode, int nextTFId) {

    }
}
